package com.itbaizhan.paymentdemo.controller;

import com.itbaizhan.paymentdemo.config.ZfbPayConfig;
import com.itbaizhan.paymentdemo.service.IZfbPayService;
import com.itbaizhan.paymentdemo.utils.ZfbVerifierUtils;
import com.itbaizhan.paymentdemo.vo.BaseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//支付宝
@Slf4j
@RestController
@RequestMapping("api/zfb-pay")
public class ZfbController {

    @Autowired
    private IZfbPayService iZfbPayService;

    @Autowired
    private ZfbPayConfig zfbPayConfig;

    //发送下单请求
    @PostMapping("pcpay/{orderNo}")
    public BaseResult zfbPay(@PathVariable String orderNo){
        BaseResult result = iZfbPayService.pcPay(orderNo);
        return result;
    }

    //支付成功后的回调  ，接收支付宝返回来的参数
    @PostMapping("pcPay/notify")
    public  String pcPaynotify(HttpServletRequest request){

        //在支付宝实现业务层的下单方法，把函数回调了，回调到一个地址，现在请求这地址就有了参数
        //System.out.println(request);
        //验签
        boolean vaild = ZfbVerifierUtils.isVaild(request, zfbPayConfig.getPublicKey());
        if(vaild){
           //验证通过修改订单状态
            iZfbPayService.updateOrderStatus(request);
        }else {
           // System.out.println("验证失败");
            log.info("支付宝验签失败");
            return "fail";
        }

        return "success";
    }


    /**
     * 申请退款
     * @param orderNo
     * @param reason
     * @return
     */
    @PostMapping("/refund/{orderNo}/{reason}")
    public BaseResult refund(@PathVariable String orderNo,@PathVariable String reason){

        iZfbPayService.refund(orderNo,reason);
        return BaseResult.ok();
    }

    @GetMapping("queryOrder/{orderNo}")
    public BaseResult queryOrderStatus(@PathVariable String orderNo) throws Exception {
        return BaseResult.ok(iZfbPayService.queryOrderStatus(orderNo));
    }
}
